#include "StdAfx.h"
#include "FilerFrogFilesListSorter.h"
#include "../FilesRefactor/FileMachine.h"

FilerFrogFilesListSorter::FilerFrogFilesListSorter(list<wstring>& filesList):
m_filesList(filesList)
{
}

FilerFrogFilesListSorter::~FilerFrogFilesListSorter()
{
}

void FilerFrogFilesListSorter::SortListRandom(std::list<wstring> &retVal)
{
	list<wstring> tmpList(m_filesList);

	while (!tmpList.empty())
	{
		int rand_int = rand()*tmpList.size();

		int i=0;

		for (list<wstring>::iterator iter=tmpList.begin(); iter!=tmpList.end(); iter++)
		{
			if (i == rand_int)
			{
				retVal.push_back(*iter);
				tmpList.remove(*iter);
				break;
			}
			i++;
		}
	}
}

// file paths comparison, not case sensitive.
bool FilerFrogFilesListSorter::CompareFilePaths(wstring first, wstring second)
{
	FileMachine fmfirst(NULL, first);
	FileMachine fmsecond(NULL, second);

	wstring tmpfirst(L"");
	wstring tmpsecond(L"");
	fmfirst.NamePlusExt(tmpfirst);
	fmsecond.NamePlusExt(tmpsecond);

	unsigned int i=0;

	while ((i<tmpfirst.length()) && (i<tmpsecond.length()) )
	{
		if (tolower(tmpfirst[i])<tolower(tmpsecond[i]))
		{
			return true;
		}
		else if (tolower(tmpfirst[i])>tolower(tmpsecond[i]))
		{
			return false;
		}

		++i;
	}

	if (tmpfirst.length()<tmpsecond.length())
	{
		return true;
	}
	else
	{
		return false;
	}
}

void FilerFrogFilesListSorter::SortListByName(std::list<wstring> &retVal)
{
	retVal = m_filesList;
	retVal.sort(CompareFilePaths);
}

// FILETIME comparison.
bool FilerFrogFilesListSorter::CompareFileTimes(wstring first, wstring second)
{
	WIN32_FIND_DATA FileData;
	HANDLE hFind;

	// processing first file
	hFind =	FindFirstFile(first.c_str(), &FileData);

	if (hFind == INVALID_HANDLE_VALUE)
	{
		wcout << L"FilerFrogListSorter::compareFilePaths: FindFirstFile failed for first." << endl;
		return false;
	}

	FILETIME ftfirst = FileData.ftCreationTime;
	FindClose(hFind);

	// processing second file
	hFind =	FindFirstFile(second.c_str(), &FileData);
	if (hFind == INVALID_HANDLE_VALUE)
	{
		wcout << L"FilerFrogListSorter::compareFilePaths: FindFirstFile failed for second." << endl;
		return false;
	}

	FILETIME ftsecond = FileData.ftCreationTime;
	FindClose(hFind);

	// comparing and returning result
	return CompareFileTime(&ftfirst, &ftsecond)<0;
}

void FilerFrogFilesListSorter::SortListFileDate(std::list<wstring> &retVal)
{
	retVal = m_filesList;
	retVal.sort(CompareFileTimes);
}